package com.bullbuddy.util;

import java.sql.Connection;
import java.util.Properties;

import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnection;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.KeyedObjectPoolFactory;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.commons.pool.impl.StackKeyedObjectPoolFactory;

public class DataSourceUtil {
	private static PoolingDataSource ds;
	public static void setup(String connectURI, Properties props) throws ClassNotFoundException {
		Class.forName(props.getProperty("driver"));
		ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
				connectURI, props);
		ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<PoolableConnection>();
		KeyedObjectPoolFactory stmtPoolFactory = new StackKeyedObjectPoolFactory();
		PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
				connectionFactory, connectionPool, stmtPoolFactory, null,// query
																			// validation
				false,// read only
				true);// auto commit

		ds = new PoolingDataSource(connectionPool);
	}

	public static Connection getConnection() {
		try {
			return ds.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
